package curl

import (
	"github.com/PuerkitoBio/goquery"
	"io"
	"net/http"
	"net/url"
	"strings"
)

// Info 获取详情页信息
func Info(p Product) (map[string]string, error) {

	// http://www.huananzhi.com/more.php?lm=10&id=365

	query := url.Values{}
	query.Add("lm", p.LM)
	query.Add("id", p.Id)

	u := url.URL{
		Scheme:   "http",
		Host:     BASE_URL,
		Path:     "/more.php",
		RawQuery: query.Encode(),
	}

	resp, err := http.Get(u.String())
	if err != nil {
		return nil, err
	}

	htmlData, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	_ = resp.Body.Close()

	// Load the HTML document
	doc, err := goquery.NewDocumentFromReader(strings.NewReader(string(htmlData)))
	if err != nil {
		return nil, err
	}

	result := make(map[string]string)
	// Find the review items
	doc.Find(".content").Find("table tr").Each(func(i int, s *goquery.Selection) {

		title := strings.TrimSpace(s.Find(".MsoNormal").First().Text())
		value := strings.TrimSpace(s.Find(".MsoNormal").Eq(1).Text())
		result[title] = value
	})

	return result, nil
}
